package com.study.redis.article.service.Impl;

import com.study.redis.article.domain.Article;
import com.study.redis.article.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

import java.lang.reflect.Method;
import java.util.*;

/**
 * Created by hegy on 2018/6/4.
 */
@Service("articleService")
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ShardedJedisPool jedisPool;

    @Override
    public List<Article> listArticle(String type) {
        List<Article> articleList = new ArrayList<>();
        try(ShardedJedis jedis = jedisPool.getResource();) {
            Set<String> artList = null;
            if ("score".equals(type)) {
                artList = jedis.zrevrange("artvote:", 0, -1);
            } else {
                artList = jedis.zrevrange("arttime:", 0, -1);
            }
            for (String artKey : artList) {
                Map<String, String> dataMap = jedis.hgetAll(artKey);
                Article article = new Article();
                article.setArtId(dataMap.get("artId"));
                article.setArtName(dataMap.get("artName"));
                article.setAuther(dataMap.get("auther"));
                article.setPubTime(dataMap.get("pubTime"));
                article.setVotes(dataMap.get("votes"));
                articleList.add(article);
            }
        } catch (Exception e) {}
        finally {
            return articleList;
        }
    }

    @Override
    public void addArticle(Article article) {
        try(ShardedJedis jedis = jedisPool.getResource();) {
            //检查文章计数器是否存在，存在加1
            if (jedis.exists("artCount")) {
                jedis.incr("artCount");
            } else {
                jedis.set("artCount", "1");
            }
            String artId = jedis.get("artCount");
            String artKey = "article:" + artId;
            //添加新文章信息
            Map<String,String> listMap = new HashMap<String,String>() {{
                put("artId", artId);
                put("artName", article.getArtName());
                put("auther", article.getAuther());
                put("pubTime", String.valueOf(System.currentTimeMillis()));
                put("votes", "0");
            }};
            jedis.hmset(artKey, listMap);
            //创建新文章的投票用户表，及将新文章加入时间/分数文章列表中
            jedis.sadd("votes:" + artId, "");
            //设置投票用户表过期时间
            jedis.expire("votes:" + artId, 86400*7);
            jedis.zadd("artvote:", Integer.valueOf(jedis.get("artCount")), artKey);
            jedis.zadd("arttime:", System.currentTimeMillis(), artKey);
        } catch (Exception e) {}
    }

    @Override
    public boolean delArticle(String artId) {
        boolean result = true;
        try (ShardedJedis jedis = jedisPool.getResource()){
            jedis.zrem("artvote:", "article:" + artId);
            jedis.zrem("arttime:", "article:" + artId);
            jedis.del("vote:" + artId);
            jedis.del("article:"+ artId);
        } catch (Exception e) {
            result = false;
        } finally {
            return result;
        }
    }

    @Override
    public boolean voteArticle(String artId, Integer id) {
        boolean result = true;
        try (ShardedJedis jedis = jedisPool.getResource()) {
            Boolean ifTimeout = jedis.exists("votes" + artId);
            Boolean ifVoted = jedis.sismember("votes:" + artId, "User:" + id);
            if (ifTimeout || ifVoted) {
                result = false;
            } else {
                jedis.sadd("votes:"+ artId, "User:" + id);
                jedis.hincrBy("article:" + artId, "votes", 1);
                jedis.zincrby("artvote:", 432 , "article:" + artId);
            }
        } catch (Exception e) {
            result = false;
        } finally {
            return result;
        }
    }
}
